package com.lwp.testjpush;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.NotificationTarget;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.support.v4.app.NotificationCompat.PRIORITY_MAX;

/**
 * Created by ch999android on 2018/6/6.
 */

public class NotificationsUtils {
    private final static String TAG = NotificationsUtils.class.getSimpleName();
    private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
    private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
    private static final double COLOR_THRESHOLD = 180.0;
    private static int titleColor;

    /**
     * 发送通知
     *
     * @param context
     * @param message
     */
    public static void notifyNotification(Context context, String message) {

        try {
            //解析收到的json消息
            JSONObject json = new JSONObject(message);
            JSONObject custommsg = json.getJSONObject("customMsg");

            //初始化自定义布局（展开布局）
            final RemoteViews remoteViews;
            int type =  isDarkNotificationBar(context);
            if (type == 1) {
                remoteViews = new RemoteViews(context.getPackageName(), R.layout.white_customer_notitfication_layout);

            } else if(type == 2){
                remoteViews = new RemoteViews(context.getPackageName(), R.layout.dark_customer_notitfication_layout);

            }else{
                remoteViews = new RemoteViews(context.getPackageName(), R.layout.customer_notitfication_layout);

            }
            remoteViews.setTextViewText(R.id.title, custommsg.getString("title"));
            remoteViews.setTextViewText(R.id.content, custommsg.getString("text"));


            //初始化通知api
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

            builder.setSmallIcon(R.mipmap.icon_default)
                    .setPriority(PRIORITY_MAX);
            Notification notification = builder.build();
            //4.1以上支持大布局模式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                notification.bigContentView = remoteViews;
            }
            //收缩后的view
            RemoteViews smallViews;
            if (type == 1) {
                smallViews = new RemoteViews(context.getPackageName(), R.layout.white_small_customer_notitfication_layout);
            } else if(type == 2){
                smallViews = new RemoteViews(context.getPackageName(), R.layout.dark_small_customer_notitfication_layout);
            }else{
                smallViews = new RemoteViews(context.getPackageName(), R.layout.small_customer_notitfication_layout);
            }

            smallViews.setTextViewText(R.id.title, custommsg.getString("title"));

            notification.contentView = smallViews;

            NotificationManager notifacationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            //发送通知
            notifacationManager.notify(2, notification);

            NotificationTarget notificationTarget = new NotificationTarget(
                    context,
                    remoteViews,
                    R.id.imageview,
                    notification,
                    2);

            Glide
                    .with(context.getApplicationContext()) // safer!
                    .load(custommsg.getString("image"))
                    .asBitmap()
                    .into(notificationTarget);

            NotificationTarget notificationTarget2 = new NotificationTarget(
                    context,
                    smallViews,
                    R.id.imageview,
                    notification,
                    2);

            Glide
                    .with(context.getApplicationContext()) // safer!
                    .load(custommsg.getString("image"))
                    .asBitmap()
                    .into(notificationTarget2);


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 1-浅色背景，2-深色背景，0-判断报错，默认白色底
     * @return
     */
    public static int isDarkNotificationBar(Context context) {
        try {
            return isColorsimilar(Color.BLACK, getNotificationColor(context)) ? 1 : 2;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    private static int getNotificationColor(Context context) {
        if (context instanceof AppCompatActivity) {
            return NotificationsUtils.getNotificationColorCompat(context);
        } else {
            return NotificationsUtils.getNotificationColorInternal(context);
        }
    }

    public static boolean isColorsimilar(int baseColor, int color) {
        int simpleBaseColor = baseColor | 0xff000000;
        int simpleColor = color | 0xff000000;
        int baseRed = Color.red(simpleBaseColor) - Color.red(simpleColor);
        int baseGreen = Color.green(simpleBaseColor) - Color.green(simpleColor);
        int baseBlue = Color.blue(simpleBaseColor) - Color.blue(simpleColor);
        double value = Math.sqrt(baseRed * baseRed + baseGreen * baseGreen + baseBlue * baseBlue);
        if (value < 180.0) {
            return true;
        }
        return false;
    }


    /**
     * 判断通知栏背景颜色，现在手机通知栏大部分不是白色就是黑色背景
     *
     * @param context
     * @return
     */
    public static boolean isDarkNotiFicationBar(Context context) {
        return !isColorSimilar(Color.BLACK, getNotificationColor(context));
    }


    private static boolean isColorSimilar(int baseColor, int color) {
        int simpleBaseColor = baseColor | 0xff000000;
        int simpleColor = color | 0xff000000;
        int baseRed = Color.red(simpleBaseColor) - Color.red(simpleColor);
        int baseGreen = Color.green(simpleBaseColor) - Color.green(simpleColor);
        int baseBlue = Color.blue(simpleBaseColor) - Color.blue(simpleColor);
        double value = Math.sqrt(baseRed * baseRed + baseGreen * baseGreen + baseBlue * baseBlue);
        if (value < COLOR_THRESHOLD) {
            return true;
        }
        return false;
    }

    public static int getNotificationColorInternal(Context context) {
        final String DUMMY_TITLE = "DUMMY_TITLE";
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentText(DUMMY_TITLE);
        Notification notification = builder.build();
        ViewGroup notificationRoot = (ViewGroup) notification.contentView.apply(context, new FrameLayout(context));
        final TextView titleView = (TextView) notificationRoot.findViewById(android.R.id.title);
        if (titleView == null) {
            iteratoryView(notificationRoot, new Filter() {
                @Override
                public void filter(View view) {
                    if (view instanceof TextView) {
                        TextView textView = (TextView) view;
                        if (DUMMY_TITLE.equals(textView.getText().toString())) {
                            titleColor = textView.getCurrentTextColor();
                        }
                    }
                }
            });
            return titleColor;
        } else {
            return titleView.getCurrentTextColor();
        }

    }

    public static int getNotificationColorCompat(Context context) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        Notification notification = builder.build();
        int layoutId = notification.contentView.getLayoutId();
        ViewGroup notificationRoot = (ViewGroup) LayoutInflater.from(context).inflate(layoutId, null);
        final TextView titleView = (TextView) notificationRoot.findViewById(android.R.id.title);
        if (titleView == null) {
            final List<TextView> textViews = new ArrayList<>();
            iteratoryView(notificationRoot, new Filter() {
                @Override
                public void filter(View view) {
                    textViews.add((TextView) view);
                }
            });

            float minTextSize = Integer.MIN_VALUE;
            int index = 0;
            for (int i = 0, j = textViews.size(); i < j; i++) {
                float currentSize = textViews.get(i).getTextSize();
                if (currentSize > minTextSize) {
                    minTextSize = currentSize;
                    index = i;
                }
            }
            return textViews.get(index).getCurrentTextColor();
        } else {
            return titleView.getCurrentTextColor();
        }
    }

    private static void iteratoryView(View view, Filter filter) {
        if (view == null || filter == null) {
            return;
        }
        filter.filter(view);
        if (view instanceof ViewGroup) {
            ViewGroup container = (ViewGroup) view;
            for (int i = 0, j = container.getChildCount(); i < j; i++) {
                View child = container.getChildAt(i);
                iteratoryView(child, filter);
            }
        }
    }

    private interface Filter {
        void filter(View view);
    }
}
